import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import { createStore } from 'vuex'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import 'element-plus/theme-chalk/dark/css-vars.css'

import App from '@/App.vue'

// 设置Element Plus暗色模式
document.documentElement.classList.add('dark')
import '@styles/index.css'
import '@fortawesome/fontawesome-free/css/all.min.css'
import Home from '@views/public/Home.vue'
import About from '@views/public/About.vue'
import CategoryArticles from '@views/public/CategoryArticles.vue'
import Login from '@views/auth/Login.vue'
import AdminLayout from '@views/admin/AdminLayout.vue'
import Dashboard from '@views/admin/Dashboard.vue'
import ArticleManagement from '@views/admin/ArticleManagement.vue'
import UserManagement from '@views/admin/UserManagement.vue'
import CategoryManagement from '@views/admin/CategoryManagement.vue'
import ArticleDetail from '@views/article/ArticleDetail.vue'
import ArticlePreview from '@views/article/ArticlePreview.vue'
import ArticleEdit from '@views/article/ArticleEdit.vue'
import Game2048Page from '@views/fun/Game2048.vue'
import QRCodeGeneratorPage from '@views/fun/QRCodeGenerator.vue'
import { authAPI } from '@api/auth.js'

// 将apiClient挂载到Vue原型上，方便在组件中使用
import { createApp as createVueApp } from 'vue'

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About },
  { path: '/category/:categoryValue', component: CategoryArticles },
  { path: '/login', component: Login },
  { path: '/article/:id', component: ArticleDetail },
  { path: '/preview/:id', component: ArticlePreview },
  { path: '/edit/:id', component: ArticleEdit, meta: { requiresAuth: true } },
  { path: '/fun/game2048', component: Game2048Page },
  { path: '/fun/qrcode', component: QRCodeGeneratorPage },
  { 
    path: '/admin', 
    component: AdminLayout,
    meta: { requiresAuth: true },
    children: [
      { path: '', redirect: '/admin/dashboard' },
      { path: 'dashboard', component: Dashboard },
      { path: 'articles', component: ArticleManagement },
      { path: 'categories', component: CategoryManagement },
      { path: 'users', component: UserManagement, meta: { requiresAdmin: true } }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

const store = createStore({
  state: {
    user: null,
    isInitialized: false
  },
  mutations: {
    setUser(state, user) {
      state.user = user
    },
    clearUser(state) {
      state.user = null
    },
    setInitialized(state, initialized) {
      state.isInitialized = initialized
    }
  },
  actions: {
    async initializeAuth({ commit, dispatch }) {
      try {
        const token = localStorage.getItem('jwt_token')
        console.log('🔐 初始化认证状态，token存在:', !!token)
        
        if (!token) {
          console.log('❌ 未找到JWT token，用户未登录')
          commit('setInitialized', true)
          return
        }
        
        console.log('🔍 验证JWT token...')
            const response = await authAPI.getCurrentUser()
        
        if (response.data.success && response.data.user) {
          console.log('✅ JWT token验证成功，用户:', response.data.user.username)
          commit('setUser', response.data.user)
        } else {
          console.log('❌ 服务器返回无效用户数据')
          localStorage.removeItem('jwt_token')
        }
      } catch (error) {
        console.log('❌ 认证初始化错误:', error.message)
        localStorage.removeItem('jwt_token')
      } finally {
        console.log('✅ 认证状态初始化完成')
        commit('setInitialized', true)
      }
    }
  },
  getters: {
    isLoggedIn: state => !!state.user,
    isAdmin: state => state.user && state.user.isAdmin
  }
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 等待认证状态初始化完成
  if (!store.state.isInitialized) {
    await store.dispatch('initializeAuth')
  }
  
  // 检查是否需要认证
  if (to.meta.requiresAuth && !store.state.user) {
    next('/login')
  } else if (to.meta.requiresAdmin && (!store.state.user || !store.state.user.isAdmin)) {
    next('/admin/dashboard')
  } else {
    next()
  }
})

const app = createApp(App)
app.use(router)
app.use(store)
app.use(ElementPlus)
app.config.globalProperties.$api = { auth: authAPI }

// 在应用挂载前初始化认证状态
async function initializeApp() {
  await store.dispatch('initializeAuth')
  app.mount('#app')
}

initializeApp()
